const Router = require('koa-router');
const { pool } = require('../config/db');
const { verifyToken, getTokenFromRequest } = require('../utils/auth');
const { v4: uuidv4 } = require('uuid');

const router = new Router({
  prefix: '/chatHistory'
});

// 使用自定义的中间件，处理token验证
const chatAuthMiddleware = async (ctx, next) => {
  const token = getTokenFromRequest(ctx);
  
  if (!token) {
    ctx.status = 401;
    ctx.body = {
      errCode: 'TOKEN_REQUIRED',
      errMsg: '未提供token',
      data: null
    };
    return;
  }
  
  const verifyResult = verifyToken(token);
  
  if (!verifyResult.valid) {
    ctx.status = 401;
    ctx.body = {
      errCode: 'TOKEN_INVALID',
      errMsg: verifyResult.message,
      data: null
    };
    return;
  }
  
  // 从token中获取用户ID
  const userId = verifyResult.payload.userId;
  
  try {
    // 查询用户信息
    const [users] = await pool.execute(
      'SELECT * FROM users WHERE id = ?',
      [userId]
    );
    
    if (users.length === 0) {
      ctx.status = 401;
      ctx.body = {
        errCode: 'USER_NOT_FOUND',
        errMsg: '用户不存在',
        data: null
      };
      return;
    }
    
    // 将用户ID保存到ctx.state中
    ctx.state.userId = users[0].id;
    
    await next();
  } catch (error) {
    ctx.status = 500;
    ctx.body = {
      errCode: 'AUTH_FAILED',
      errMsg: '验证用户信息失败：' + error.message,
      data: null
    };
  }
};

// 为所有路由添加认证中间件
router.use(chatAuthMiddleware);

/**
 * 上传聊天记录
 * POST /chatHistory/uploadChatHistory
 */
router.post('/uploadChatHistory', async (ctx) => {
  const { target, chatData } = ctx.request.body;
  
  // 参数校验
  if (!chatData) {
    ctx.status = 400;
    ctx.body = {
      errCode: 'PARAM_IS_NULL',
      errMsg: '聊天记录数据不能为空',
      data: null
    };
    return;
  }
  
  if (!target) {
    ctx.status = 400;
    ctx.body = {
      errCode: 'PARAM_IS_NULL',
      errMsg: '聊天对象不能为空',
      data: null
    };
    return;
  }
  
  try {
    // 从ctx.state获取用户ID
    const userId = ctx.state.userId;
    
    // 将JSON数据转为字符串
    const fileContent = JSON.stringify(chatData);
    const timestamp = Date.now();
    
    // 查询是否已存在该用户与目标的聊天记录
    const [existingRecords] = await pool.execute(
      'SELECT * FROM chat_history WHERE user_id = ? AND target = ?',
      [userId, target]
    );
    
    let result;
    
    // 如果存在记录，更新现有记录
    if (existingRecords.length > 0) {
      const record = existingRecords[0];
      
      result = await pool.execute(
        'UPDATE chat_history SET content = ?, update_time = ? WHERE id = ?',
        [fileContent, timestamp, record.id]
      );
    } else {
      // 如果不存在记录，创建新记录
      const historyId = uuidv4();
      result = await pool.execute(
        'INSERT INTO chat_history (id, user_id, target, content, create_time, update_time) VALUES (?, ?, ?, ?, ?, ?)',
        [historyId, userId, target, fileContent, timestamp, timestamp]
      );
    }
    
    ctx.body = {
      errCode: 0,
      errMsg: '上传聊天记录成功',
      data: null
    };
  } catch (error) {
    console.error('上传聊天记录失败', error);
    ctx.status = 500;
    ctx.body = {
      errCode: 'UPLOAD_CHAT_HISTORY_FAILED',
      errMsg: '上传聊天记录失败：' + error.message,
      data: null
    };
  }
});

/**
 * 获取用户与特定角色的聊天记录内容
 * POST /chatHistory/getTargetChatContent
 */
router.post('/getTargetChatContent', async (ctx) => {
  const { target } = ctx.request.body;
  
  // 参数校验
  if (!target) {
    ctx.status = 400;
    ctx.body = {
      errCode: 'PARAM_IS_NULL',
      errMsg: '聊天对象不能为空',
      data: null
    };
    return;
  }
  
  try {
    // 从ctx.state获取用户ID
    const userId = ctx.state.userId;
    
    // 查询数据库中的记录
    const [records] = await pool.execute(
      'SELECT * FROM chat_history WHERE user_id = ? AND target = ?',
      [userId, target]
    );
    
    // 如果记录不存在，返回空聊天记录
    if (records.length === 0) {
      ctx.body = {
        errCode: 0,
        errMsg: '没有找到聊天记录',
        data: {
          chatData: null,
          isNew: true
        }
      };
      return;
    }
    
    const record = records[0];
    
    // 解析内容
    const chatData = JSON.parse(record.content);
    
    ctx.body = {
      errCode: 0,
      errMsg: '获取聊天记录成功',
      data: {
        chatData,
        isNew: false,
        updateTime: record.update_time
      }
    };
  } catch (error) {
    console.error('获取聊天记录失败', error);
    ctx.status = 500;
    ctx.body = {
      errCode: 'GET_CHAT_FAILED',
      errMsg: '获取聊天记录失败：' + error.message,
      data: null
    };
  }
});

/**
 * 删除与特定角色的聊天记录
 * POST /chatHistory/deleteChatHistoryByTarget
 */
router.post('/deleteChatHistoryByTarget', async (ctx) => {
  const { target } = ctx.request.body;
  
  // 参数校验
  if (!target) {
    ctx.status = 400;
    ctx.body = {
      errCode: 'PARAM_IS_NULL',
      errMsg: '聊天对象不能为空',
      data: null
    };
    return;
  }
  
  try {
    // 从ctx.state获取用户ID
    const userId = ctx.state.userId;
    
    // 删除聊天记录
    const [result] = await pool.execute(
      'DELETE FROM chat_history WHERE user_id = ? AND target = ?',
      [userId, target]
    );
    
    if (result.affectedRows > 0) {
      ctx.body = {
        errCode: 0,
        errMsg: '删除聊天记录成功',
        data: {
          success: true
        }
      };
    } else {
      ctx.body = {
        errCode: 0,
        errMsg: '没有找到要删除的聊天记录',
        data: {
          success: false
        }
      };
    }
  } catch (error) {
    console.error('删除聊天记录失败', error);
    ctx.status = 500;
    ctx.body = {
      errCode: 'DELETE_FAILED',
      errMsg: '删除聊天记录失败：' + error.message,
      data: null
    };
  }
});

module.exports = router; 